/**
 * Created by baidm in 2021/2/6 on 12:47
 */
/**
 * leetcode第五题：最长回文子串
 * input:s="babad",out:"bab"或"aba"
 * input:s="cbbd",out:"bb"
 * input:s="a",out:"a"
 * input:s="ac",out:"a"
 * @param s
 * @returns {string}
 * 算法：中心扩展算法
 * 思路：计算最大串的函数getMax，计算完毕后返回最大串索引left和right，比较两种情况返回的差值，取最大的赋值给start和end
 */
function maxSubPalindrome(s = "") {
    let len = s.length;

    function getMax(left, right) {
        while (left >= 0 && right < len && s[left] === s[right]) {
            left--;
            right++;
        }
        return {
            left: left + 1,
            right: right - 1
        }
    }

    let start = 0, end = 0;
    for (let i = 0; i < len; i++) {
        let obj1 = getMax(i, i); // ...aba...类型
        let obj2 = getMax(i, i + 1); // ...abba...类型
        let flag = obj1.right - obj1.left > obj2.right - obj2.left;
        let maxObj = flag ? obj1 : obj2;
        if (maxObj.right - maxObj.left > end - start) {
            start = maxObj.left;
            end = maxObj.right;
        }
    }
    return s.slice(start, end + 1);
}